<?php
// +----------------------------------------------------------------------
// |微信公共类
// +----------------------------------------------------------------------
// |Data:2014-11-25-下午8:51
// +----------------------------------------------------------------------
// |Author: 吕志雄 <870923001@qq.com>
// +----------------------------------------------------------------------
namespace Common\Org\Chat;
class WeiXin{
    protected $appid;
    protected $appsecret;
    protected $access_token;

    /**
     * 构造方法
     * @param $appid
     * @param $appsecret
     */
    public function __construct($appid,$appsecret){
        if(empty($appid) || empty($appsecret)){
            return array('errcode'=>-1,'errmsg'=>'参数为空！');
        }

        $this->appid = $appid;
        $this->appsecret = $appsecret;
        //获取access_token
        $this->access_token = $this->get_access_token();
    }

    /**
     * 获取access_token
     * @return array|mixed
     */
    private function get_access_token(){
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
        $res = $this->https_request($url);
        $result = json_decode($res, true);
        if(empty($result['access_token'])){
            return false;
        }
        $access_token = $result["access_token"];


        /*if(!S('access_token_'.$this->appid)){
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appid&secret=$this->appsecret";
            $res = $this->https_request($url);
            $result = json_decode($res, true);
            if(empty($result['access_token'])){
                return false;
            }
            S('access_token_'.$this->appid,$result["access_token"],$result['expires_in']);
            $access_token = $result["access_token"];
        }else{
            $access_token = S('access_token_'.$this->appid);
        }*/
        return $access_token;
    }

    public function getAccessToken(){
        return $this->access_token;
    }

    /**
     * 返回错误信息
     * @return array
     */
    private function return_errmsg(){
        return array('errcode'=>-1,'errmsg'=>'参数传递错误！');
    }

    /**
     * 获取关注者列表
     * @param null $next_openid 用户的openid
     * @return mixed array
     */
    public function get_user_list($next_openid = null){
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    /**
     * 获取用户基本信息
     * @param $openid 用户openid
     * @return mixed array
     */
    public function get_user_info($openid){
        if(empty($openid)){
            $this->return_errmsg();
        }
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->access_token."&openid=".$openid."&lang=zh_CN";
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    /**
     * 创建菜单
     * @param $data 菜单数据（json格式）
     * @return mixed array
     */
    public function create_menu($data){
        if(empty($data) || !is_array($data)){
            $this->return_errmsg();
        }
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    /**
     * 删除菜单
     * @return mixed array
     */
    public function delete_menu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=".$this->access_token;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    /**
     * 查询菜单
     * @return mixed
     */
    public function find_menu(){
        $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=".$this->access_token;
        $res = $this->https_request($url);
        return json_decode($res, true);
    }

    /**
     * 创建分组
     * @param $group_name 分组名称
     * @return mixed array
     */
    public function create_group($group_name){
        if(empty($group_name)){
            $this->return_errmsg();
        }
        $data = '{"group": {"name": "'.$group_name.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    /**
     * 移动用户分组
     * @param $openid 用户openid
     * @param $to_groupid 分组id
     * @return mixed array
     */
    public function move_group($openid,$to_groupid ){
        if(empty($openid) || empty($to_groupid)){
            $this->return_errmsg();
        }
        $data = '{"openid":"'.$openid.'","to_groupid":'.$to_groupid.'}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        return json_decode($res, true);
    }

    /**
     * 查询所有分组
     * @return mixed array
     */
    public function get_group(){
        $url = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=".$this->access_token;
        $res = $this->https_request($url);
        return json_decode($res,true);
    }

    /**
     * 查询用户所在分组
     * @param $openid openid
     * @return mixed array
     */
    public function get_group_by_openid($openid){
        if(empty($openid)){
            $this->return_errmsg();
        }
        $data ='{"openid":"'.$openid.'"}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=".$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 批量移动分组
     * @param $openids 用户的openid多个用逗号隔开
     * @param $to_groupid 目标分组ID
     * @return bool|mixed
     */
    public function move_all_group($openids,$to_groupid){
        if(empty($openids) || is_array($openids)) return false;
        $data = array(
            'openid_list'=>str2arr($openids)
        );
        $data['to_groupid'] = $to_groupid;
        $url = "https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=".$this->access_token;
        $result = JSON($data);
        $res = $this->https_request($url,$result);
        return json_decode($res,true);
    }

    /**
     * 修改分组名
     * @param $group_id 分组id
     * @param $group_name 分组名称
     * @return mixed array
     */
    public function update_group($group_id,$group_name){
        if(empty($group_id) || empty($group_name)){
            $this->return_errmsg();
        }
        $data = '{"group":{"id":'.$group_id.',"name":"'.$group_name.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/update?access_token=".$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 删除分组
     * @param $group_id
     * @return mixed
     */
    public function delete_group($group_id){
        if(empty($group_id)){
            $this->return_errmsg();
        }
        $data = '{"group":{"id":"'.$group_id.'"}}';
        $url = "https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=".$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 设置备注
     * @param $openid openid
     * @param $remark 备注名称
     * @return mixed array
     */
    public function set_remark($openid,$remark){
        if(empty($openid) || empty($remark)){
            $this->return_errmsg();
        }
        $data = '{"openid":"'.$openid.'","remark":"'.$remark.'"}';
        $url = "https://api.weixin.qq.com/cgi-bin/user/info/updateremark?access_token=".$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 获取关注列表
     * @param string $next_openid
     * @return mixed
     */
    public function get_subscribe_list($next_openid=''){
        $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token."&next_openid=".$next_openid;
        $res = $this->https_request($url);
        return json_decode($res,true);
    }

    /**
     * 发送客服消息
     * @param $openid openid
     * @param $msg_type 类型
     * @param $data 发送数据
     * @return mixed array
     */
    public function send_custom_message($openid,$msg_type,$data){
        if(empty($openid) || empty($msg_type) || empty($data)){
            $this->return_errmsg();
        }
        $msg = array();
        $msg['touser'] = $openid;
        switch($msg_type){
            case 'text'://文本
                $msg['text'] = array('content'=>$data['content']);
                break;
            case 'image'://图片
                $msg['image'] = array('media_id',$data['media_id']);
                break;
            case 'voice'://音频
                $msg['voice'] = array('media_id',$data['media_id']);
                break;
            case 'video'://视频
                $msg['video'] = array('media_id',$data['media_id']);
                $msg['video'] = array('thumb_media_id',$data['thumb_media_id']);
                $msg['video'] = array('title',$data['title']);
                $msg['video'] = array('description',$data['description']);
                break;
            case 'music'://音乐
                $msg['music'] = array('title',$data['title']);
                $msg['music'] = array('description',$data['description']);
                $msg['music'] = array('musicurl',$data['musicurl']);
                $msg['music'] = array('hqmusicurl',$data['hqmusicurl']);
                $msg['music'] = array('thumb_media_id',$data['media_id']);
                break;
            case 'news'://图文
                $tempArray = array();
                foreach($data as $val){
                    $tempArray['title'] = $val['title'];
                    $tempArray['description'] = $val['description'];
                    $tempArray['url'] = $val['url'];
                    $tempArray['picurl'] = $val['picurl'];
                    array_push($msg['news']['articles'],$tempArray);
                }

                break;
            default:
                return '未知消息类型'.$msg_type;
                break;
        }
        $msg['msgtype'] = $msg_type;
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->access_token;
        $data = JSON($msg);
        $res = $this->https_request($url, $data);
        return json_decode($res, true);

    }

    /**
     * 获取多客服聊天记录
     * @param $open_id 用户的标识
     * @param $starttime 查询开始时间
     * @param $endtime 查询结束时间
     * @param $pageindex 查询第几页，从1开始
     * @param int $pagesize 每页大小 每页最多拉取1000条
     * @return array
     */
    public function get_more_custom_list($open_id,$starttime,$endtime,$pageindex = 1,$pagesize = 10){
        if(empty($open_id) || empty($starttime) || empty($endtime)){
            $this->return_errmsg();
        }
        $url = "https://api.weixin.qq.com/cgi-bin/customservice/getrecord?access_token=".$this->access_token;
        $data = '{"starttime" : '.$starttime.',"endtime" : '.$endtime.',"openid":"'.$open_id.'","pagesize" : '.$pagesize.',"pageindex" : '.$pageindex.'}';
        $res = $this->https_request($url,$data);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 群发信息
     * @param $msg_type 消息类型
     * @param $data 群发数据
     * @param int $group_type 发送类型
     * @return mixed|string
     */
    public function mass_send_message($msg_type,$data,$group_type = 1){
        if(empty($msg_type) || empty($data) || !is_array($data)){
            $this->return_errmsg();
        }
        $msg = array();
        if($group_type == 1){//分组进行群发
            $msg['filter'] = array('group_id',$data['group_id']);
            $msg['is_to_all'] = False;
            $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=".$this->access_token;
        }else{//OpenID列表群发
            $temp = explode(',',$data["openids"]);
            $msg['touser'] = $temp;//逗号分割
            $url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token=".$this->access_token;
        }

        switch($msg_type){
            case 'text'://文本
                $msg['text']['content'] = $data['content'];
                break;
            case 'image'://图片
                $msg['image']['media_id'] = $data['media_id'];
                break;
            case 'voice'://音频
                $msg['voice']['media_id'] = $data['media_id'];
                break;
            case 'mpvideo'://视频
                $msg['mpvideo']['media_id'] = $data['media_id'];
                break;
            case 'mpnews'://图文
                $msg['mpnews']['media_id'] = $data['media_id'];
                break;
            default:
                return '未知消息类型：'.$msg_type;
                break;
        }

        $msg['msgtype'] = $msg_type;
        $res = $this->https_request($url,JSON($msg));
        return json_decode($res, true);
    }

    /**
     * 查询群发消息发送状态
     * @param $msg_id
     * @return mixed
     */
    public function get_mass_status($msg_id){
        if(empty($msg_id)){
            $this->return_errmsg();
        }
        $data = '{"msg_id": "'.$msg_id.'"}';
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/get?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 删除群发
     * @param $msg_id 群发消息ID
     * @return mixed
     */
    public function delete_mass($msg_id){
        if(empty($msg_id)){
            $this->return_errmsg();
        }
        $data = '{"msg_id":'.$msg_id.'}';
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/delete?access_token=".$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 生成参数二维码
     * @param $scene_type 类型
     * @param $scene_id 场景值ID
     * @return string 图片资源
     */
    public function create_qrcode($scene_type, $scene_id){
        if(empty($scene_type) || empty($scene_id)){
            $this->return_errmsg();
        }
        switch($scene_type){
            case 'QR_LIMIT_SCENE': //永久
                $data = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
            case 'QR_SCENE':       //临时
                $data = '{"expire_seconds": 1800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene_id.'}}}';
                break;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$this->access_token;
        $res = $this->https_request($url, $data);
        $result = json_decode($res, true);
        return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($result["ticket"]);
    }

    /**
     * 上传 多媒体文件
     * @param $fileData 文件数据 ，如：dirname(__FILE__).'\winter.jpg'
     * @param string $type 类型
     * @return mixed
     */
    public function upload_media($fileData,$type = 'image'){
        if(empty($fileData)){
            $this->return_errmsg();
        }

        $filedata = array('media'=>"@".$fileData);
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
        $res = $this->https_request($url,$filedata);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 上传图文消息内的图片
     * @param $fileData
     * @return mixed
     */
    public function uploadImageTextImg($fileData){
        if(empty($fileData)){
            $this->return_errmsg();
        }
        $filedata = array('media'=>"@".$fileData);
        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token='.$this->access_token;
        $res = $this->https_request($url,$filedata);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 下载多媒体文件到服务器上
     * @param $media
     * @param $savePath 保存路径
     * @return Bool
     */
    public function download_media($media,$savePath){
        if(empty($media) || empty($savePath)){
            $this->return_errmsg();
        }
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$media;
        $fileInfo = $this->downloadWeixinFile($url);

        if($fileInfo['header']['http_code']==200 && $fileInfo['header']['download_content_length']>0){

            $ext = array(
                //图片
                'image/png' => '.png',
                'image/jpeg' => '.jpg',
                'image/gif' => '.gif',
                'image/bmp' => '.bmp',
                //音频
                'audio/mpeg' => '.mp3',
                'audio/x-ms-wma'=>'.wma',
                'audio/wav'=>'.wav',
                'audio/amr'=>'.amr',
                //视频
                'application/vnd.rn-realmedia'=>'.rm',
                'application/vnd.rn-realmedia-vbr'=>'.rmvb',
                'video/x-ms-wmv'=>'.wmv',
                'video/avi'=>'.avi',
                'video/mpg'=>'.mpg',
                //'video/mpg'=>'.mpeg',
                'video/mp4'=>'.mp4'

            );
            $content_type = $fileInfo['header']['content_type'];
            $saveName = $savePath.(time()+rand(10000,99999)).$ext[$content_type];

            $local_file = fopen($saveName, 'w');
            if (false !== $local_file){
                if (false !== fwrite($local_file,$fileInfo['body'])) {
                    fclose($local_file);
                }
            }

        }else{
            return false;
        }


    }

    /**
     *下载到本地电脑
     */
    public function downMedia($media_id){
        if(empty($media_id)){
            $this->return_errmsg();
        }
        $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->access_token."&media_id=".$media_id;
        $fileInfo = $this->downloadWeixinFile($url);
        return $fileInfo['body'];
    }

    /**
     * 上传图文消息素材
     * @param $data 上传数据
     * @return array
     */
    public function upload_news($data){
        if(empty($data) || !is_array($data)){
            $this->return_errmsg();
        }
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$this->access_token;
        $msg = array();
        if($data && is_array($data)){
            $tempArray = array();
            foreach($data as $val){
                $tempArray['thumb_media_id'] = $val['thumb_media_id'];
                $tempArray['author'] = $val['author'];
                $tempArray['title'] = $val['title'];
                $tempArray['content_source_url'] = $val['content_source_url'];
                $tempArray['content'] = addslashes($val['content']);
                $tempArray['digest'] = $val['digest'];
                $tempArray['show_cover_pic'] = $val['show_cover_pic'];
                $msg['articles'][] = $tempArray;
            }
        }

        $json_data = JSON($msg);
        $res = $this->https_request($url,$json_data);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 新增永久图文消息素材
     * @param $data
     */
    public function add_news($data){
        if(empty($data) || !is_array($data)){
            $this->return_errmsg();
        }

        $url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token=".$this->access_token;
        $msg = array();
        if($data && is_array($data)){
            $tempArray = array();
            foreach($data as $val){
                $tempArray['thumb_media_id'] = $val['thumb_media_id'];
                $tempArray['author'] = $val['author'];
                $tempArray['title'] = $val['title'];
                $tempArray['content_source_url'] = $val['content_source_url'];
                $tempArray['content'] = $val['content'];
                $tempArray['digest'] = $val['digest'];
                $tempArray['show_cover_pic'] = $val['show_cover_pic'];
                $msg['articles'][] = $tempArray;
            }
        }

        $json_data = JSON($msg);
        $res = $this->https_request($url,$json_data);
        $result = json_decode($res,true);
        return $result;
    }

    /**
     * 预览接口
     * @param $openid
     * @param $media_id
     * @return bool|mixed
     */
    public function preview($openid,$media_id){
        if(empty($openid) || empty($media_id)) return false;
        $url = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=".$this->access_token;
        $data = '{"touser":"'.$openid.'","mpnews":{"media_id":"'.$media_id.'"},"msgtype":"mpnews"}';
        $result = $this->https_request($url,$data);
        return json_decode($result,true);
    }

    /**
     * 上传视频获取media_id（群发）
     * @param $data 提交的数据（array）
     * @return mixed
     */
    public function upload_video($data){
        if(empty($data)){
            $this->return_errmsg();
        }
        $url = "https://file.api.weixin.qq.com/cgi-bin/media/uploadvideo?access_token=".$this->access_token;
        $res = $this->https_request($url,json_encode($data));
        $result = json_decode($res,true);
        return $result;
    }

//===========================================================商品分组=======================================
    /**
     * 添加分组
     * @param $group_name 分组名称
     * @param $product_list 商品ID集合，多个逗号隔开
     * @return mixed array
     */
    public function add_shop_group($group_name,$product_list){
        if(empty($group_id) || empty($product_list)){
            $this->return_errmsg();
        }

        $data = '{
        "group_detail" : {
        "group_name": "'.trim($group_name,',').'",
        "product_list" : ['.trim($product_list,',').']}
        }';
        $url = 'https://api.weixin.qq.com/merchant/group/add?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 删除分组
     * @param $group_id 分组ID
     * @return mixed array
     */
    public function del_shop_group($group_id){
        if(empty($group_id)){
            $this->return_errmsg();
        }

        $data = '{"group_id": '.intval($group_id).'}';
        $url = 'https://api.weixin.qq.com/merchant/group/del?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 修改分组属性
     * @param $group_id 分组ID
     * @param $group_name 分组名称
     * @return mixed array
     */
    public function update_shop_group($group_id,$group_name){
        if(empty($group_id) || empty($group_name)){
            $this->return_errmsg();
        }

        $data = '{"group_id": '.intval($group_id).',"group_name":"'.$group_name.'"}';
        $url = 'https://api.weixin.qq.com/merchant/group/propertymod?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 修改分组商品
     * @param $group_id 分组ID
     * @param $product 分组的商品集合(product_id 商品ID, mod_action 修改操作(0-删除, 1-增加))
     * @return bool|mixed array
     */
    public function update_shop_mod($group_id,$product){
        if(empty($group_id) || empty($product)){
            $this->return_errmsg();
        }

        $str = '{';
        $str .='"group_id": '.intval($group_id).',';
        $str .='"product":[';
        foreach($product as $key=>$val){
            $douhao = $key != 0 ? ',' : '';
            $str .=$douhao.'{';
            $str .='"product_id":"'.$val['product_id'].'",';
            $str .='"mod_action": '.$val['mod_action'].'';
            $str .='}';
        }
        $str .=']';
        $str .='}';

        $url = 'https://api.weixin.qq.com/merchant/group/productmod?access_token='.$this->access_token;
        $res = $this->https_request($url,$str);
        return json_decode($res,true);
    }

    /**
     * 获取所有分组
     * @return mixed array
     */
    public function get_all_shop_group(){
        $url = 'https://api.weixin.qq.com/merchant/group/getall?access_token='.$this->access_token;
        $res = $this->https_request($url);
        return json_decode($res,true);
    }

    /**
     * 根据分组ID获取分组信息
     * @param $group_id 分组ID
     * @return mixed array
     */
    public function get_group_by_id($group_id){
        if(empty($group_id)){
            $this->return_errmsg();
        }

        $data = '{"group_id": '.$group_id.'}';
        $url = 'https://api.weixin.qq.com/merchant/group/getbyid?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

//===========================================================商品管理接口=======================================
    /**
     * 删除商品
     * @param $product_id 商品ID
     * @return mixed array
     */
    public function del_shop_by_id($product_id){
        if(empty($product_id)){
            $this->return_errmsg();
        }

        $data = '{"product_id": "'.$product_id.'"}';
        $url = 'https://api.weixin.qq.com/merchant/del?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 查询商品
     * @param $product_id 商品ID
     * @return mixed array
     */
    public function select_shop_by_id($product_id){
        if(empty($product_id)){
            $this->return_errmsg();
        }

        $data = '{"product_id": "'.$product_id.'"}';
        $url = 'https://api.weixin.qq.com/merchant/get?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 获取指定状态的所有商品
     * @param $status 商品状态(0-全部, 1-上架, 2-下架)
     * @return mixed array
     */
    public function get_shop_by_status($status){
        $data = '{"status": '.$status.'}';
        $url = 'https://api.weixin.qq.com/merchant/getbystatus?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 设置商品上下架
     * @param $product_id 商品ID
     * @param $status 商品状态(0-全部, 1-上架, 2-下架)
     * @return mixed array
     */
    public function set_shop_status($product_id,$status){
        if(empty($product_id)){
            $this->return_errmsg();
        }

        $data = '{"product_id": "'.$product_id.'","status": '.$status.'}';
        $url = 'https://api.weixin.qq.com/merchant/modproductstatus?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 获取指定分类的所有子分类
     * @param $cate_id 大分类ID(根节点分类id为1)
     * @return mixed array
     */
    public function get_shop_subcate($cate_id){
        if(empty($cate_id)){
            $this->return_errmsg();
        }

        $data = '{"cate_id": '.$cate_id.'}';
        $url = 'https://api.weixin.qq.com/merchant/category/getsub?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 获取指定子分类的所有SKU
     * @param $cate_id 商品子分类ID
     * @return mixed
     */
    public function get_shop_sku($cate_id){
        if(empty($cate_id)){
            $this->return_errmsg();
        }

        $data = '{"cate_id": '.$cate_id.'}';
        $url = 'https://api.weixin.qq.com/merchant/category/getsku?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 获取指定分类的所有属性
     * @param $cate_id 分类ID
     * @return mixed
     */
    public function get_shop_property($cate_id){
        if(empty($cate_id)){
            $this->return_errmsg();
        }

        $data = '{"cate_id": '.$cate_id.'}';
        $url = 'https://api.weixin.qq.com/merchant/category/getproperty?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

//===========================================================库存管理接口=======================================

    /**
     * 增加库存
     * @param $product_id 商品ID
     * @param $sku_info 格式"id1:vid1;id2:vid2"
     * @param $quantity 增加的库存数量
     * @return mixed
     */
    public function add_inventory($product_id,$sku_info,$quantity){
        if(empty($product_id) || empty($sku_info) || empty($quantity)){
            $this->return_errmsg();
        }

        $data = '{"product_id": "'.$product_id.'", "sku_info": "'.$sku_info.'", "quantity": '.$quantity.'}';
        $url = 'https://api.weixin.qq.com/merchant/stock/add?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    /**
     * 减少库存
     * @param $product_id 商品ID
     * @param $sku_info 格式"id1:vid1;id2:vid2"
     * @param $quantity 增加的库存数量
     * @return mixed
     */
    public function reduce_inventory($product_id,$sku_info,$quantity){
        if(empty($product_id) || empty($sku_info) || empty($quantity)){
            $this->return_errmsg();
        }

        $data = '{"product_id": "'.$product_id.'", "sku_info": "'.$sku_info.'", "quantity": '.$quantity.'}';
        $url = 'https://api.weixin.qq.com/merchant/stock/reduce?access_token='.$this->access_token;
        $res = $this->https_request($url,$data);
        return json_decode($res,true);
    }

    public function getMaterial($media_id){
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='.$this->access_token.'&media_id='.$media_id;
        $res = $this->https_request($url,null,1);
        return $res;
        //return json_decode($res,true);
    }

    /**
     * 下载
     * @param $url 地址
     * @return array
     */
    private function downloadWeixinFile($url){
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $package = curl_exec($ch);
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        $imageAll = array_merge(array('header' => $httpinfo), array('body' => $package));
        return $imageAll;
    }

    /**
     * https请求（支持GET和POST）
     * @param $url 请求URL
     * @param null $data 需提交的数据
     * @return mixed
     */
    protected function https_request($url,$data = null,$type=''){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if(!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        if($type==1){
            curl_setopt($curl, CURLOPT_HEADER, true);
        }
        //curl_setopt($curl, CURLOPT_NOBODY, true);

        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}
?>